package com.auto.survey.activity.monitoring.point

import android.content.Intent
import android.graphics.Color
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.auto.survey.R
import com.auto.survey.activity.monitoring.station.CreateStationActivity.Companion.CREATE_STATION_BASE_POINT
import com.auto.survey.activity.monitoring.station.CreateStationActivity.Companion.CREATE_STATION_BASE_POINT_RESULT_OK
import com.auto.survey.activity.monitoring.station.CreateStationActivity.Companion.CREATE_STATION_BASE_POINT_TPYE
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_OBJECT_ID
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_STATION_ID
import com.auto.survey.activity.monitoring.dao.MonitoringRepository
import com.auto.survey.activity.monitoring.entity.MonitoringPoint
import com.auto.survey.activity.monitoring.entity.Point
import com.auto.survey.base.BaseActivity
import com.auto.survey.base.Command
import com.auto.survey.util.Helper
import com.auto.survey.util.Helper.formatTimestamp
import com.auto.survey.widget.CentreToast
import com.auto.survey.widget.CommonTitle.Companion.TEXT_POSITON_RIGHT
import com.auto.survey.widget.wheel.ChartsDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 添加测点
 */
class CreatePointActivity :BaseActivity(){

    private var objectId:Int = -1

    private var stationId:Int = -1
    private val database = MonitoringRepository()
    private val pointTypes = mutableListOf<String>()
    private var pointTypeSelection = 0
    private var isNeceresry = false

    override fun initView() {
        stationId = intent.getIntExtra(KEY_INTENT_STATION_ID, -1)
        objectId = intent.getIntExtra(KEY_INTENT_OBJECT_ID, -1)
        pointTypeSelection = intent.getIntExtra(CREATE_STATION_BASE_POINT_TPYE, 0)

        pointTypes.addAll(Command.pointTypaList())

        val point_name = findViewById<EditText>(R.id.edit_create_montoring_point_name)
        val point_x = findViewById<EditText>(R.id.edit_create_montoring_point_X)
        val point_y = findViewById<EditText>(R.id.edit_create_montoring_point_Y)
        val point_z = findViewById<EditText>(R.id.edit_create_montoring_point_z)
        val pointType = findViewById<TextView>(R.id.tv_create_montoring_point_type)

        pointType.text = pointTypes[pointTypeSelection]
        switchNescessStyle(pointTypeSelection, point_x, point_y, point_z)

        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.action_bar)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.action_bar)
        mComment_title?.setTitle("添加测点")

        mComment_title?.setRightTitle("保存")
        mComment_title?.setTitleColor(Color.WHITE, TEXT_POSITON_RIGHT)
        mComment_title?.setOnRightTextClickListener(Helper.debounce{

            val name = point_name.text.toString()
            if (TextUtils.isEmpty(name)) {
                CentreToast.instance.show("名称不可为空", false)
                return@debounce
            }

            val type = pointType.text.toString()
            if (TextUtils.isEmpty(type)) {
                CentreToast.instance.show("类型不可为空", false)
                return@debounce
            }

            if (objectId == -1) {
                CentreToast.instance.show("监测对象未指定", false)
                return@debounce
            }

            var x = point_x.text.toString()
            var y = point_y.text.toString()
            var z = point_z.text.toString()

            if (isNeceresry && (TextUtils.isEmpty(x) || TextUtils.isEmpty(y) || TextUtils.isEmpty(z))) {
                CentreToast.instance.show("请填写必填项", false)
                return@debounce
            }

            val creatTime = System.currentTimeMillis()

            if (TextUtils.isEmpty(x)) {
                x = "0"
            }
            if (TextUtils.isEmpty(y)) {
                y = "0"
            }
            if (TextUtils.isEmpty(z)) {
                z = "0"
            }

            val point = Point(monitoringObjectId=objectId,pointName = name,
                pointX = x.toDouble(), pointY = y.toDouble(), pointZ = z.toDouble(),pointType=type)

            lifecycleScope.launch {
                try {
                    // 创建基础点并获取ID
                    val pointId = database.createPoint(point).toInt()
                    if (pointId == -1) throw Exception("创建基础点失败")

                    // 构建监测点对象
                    val monitoringPoint = MonitoringPoint(
                        id = pointId,
                        monitoringObjectId = objectId,
                        stationId = stationId,
                        pointName = point.pointName,
                        pointX = point.pointX,
                        pointY = point.pointY,
                        pointZ = point.pointZ,
                        collected = true,
                        pointHz = null,
                        pointV = null,
                        pointSD = null,
                        mirrorHeight = 0.0,
                        pointType = point.pointType,
                        isWarning = false,
                        mirrorType = 0,
                        createTime = formatTimestamp(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"),
                        updateTime = ""
                    )

                    // 根据stationId执行不同逻辑
                    val result: Any? = if (stationId != -1) {
                        val mpid = database.createMonitoringPoint(monitoringPoint).toInt()
                        if (mpid == -1) throw Exception("创建监测点失败")
                        true // 成功标记
                    } else {
                        monitoringPoint
                    }

                    // 在主线程处理结果
                    withContext(Dispatchers.Main) {
                        CentreToast.instance.show("添加成功", true)
                        if (result is MonitoringPoint) {
                            val data = Intent().apply {
                                putExtra(CREATE_STATION_BASE_POINT, result)
                            }
                            setResult(CREATE_STATION_BASE_POINT_RESULT_OK, data)
                        }
                        finish()
                    }
                } catch (e: Exception) {
                    // 统一处理异常
                    withContext(Dispatchers.Main) {
                        CentreToast.instance.show("添加失败: ${e.message}", true)
                        finish()
                    }
                }
            }
        })


        pointType.setOnClickListener {

            val chartsDialog = ChartsDialog(this@CreatePointActivity, pointTypes, pointTypeSelection)
            chartsDialog.setTitle("选择类型")
            chartsDialog.setDiaChartsData { postion, chartsData ->
                pointTypeSelection = postion
                switchNescessStyle(postion, point_x, point_y, point_z)
                pointType.text = chartsData
            }
            chartsDialog.show()
        }
    }

    private fun switchNescessStyle(postion:Int, point_x:EditText, point_y:EditText, point_z:EditText) {
        when (postion) {
            0 -> {
                point_x.hint = "选填"
                point_y.hint = "选填"
                point_z.hint = "选填"
                isNeceresry = false
                point_x.setHintTextColor(ContextCompat.getColor(this@CreatePointActivity, R.color.hintColor))
                point_y.setHintTextColor(ContextCompat.getColor(this@CreatePointActivity, R.color.hintColor))
                point_z.setHintTextColor(ContextCompat.getColor(this@CreatePointActivity, R.color.hintColor))
            }

            1,2 -> {
                isNeceresry = true
                point_x.hint = "必填"
                point_y.hint = "必填"
                point_z.hint = "必填"

                point_x.setHintTextColor(ContextCompat.getColor(this@CreatePointActivity, android.R.color.holo_red_dark))
                point_y.setHintTextColor(ContextCompat.getColor(this@CreatePointActivity, android.R.color.holo_red_dark))
                point_z.setHintTextColor(ContextCompat.getColor(this@CreatePointActivity, android.R.color.holo_red_dark))
            }
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_create_montoring_point
    }
}